﻿using Ace.Application;
using Ace.Data;
using Ace.Entity.Wiki;
using Ace.Exceptions;
using Ace.IdStrategy;
using Chloe;
using Chloe.MySql;
using Chloe.SqlServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ace.Application.Wiki
{
    public interface IUsersChargeService : IAppService
    {

        decimal GetLeft(string UserID);
        UsersCharge Add(AddUsersChargeInput input);
        void Update(UpdateUsersChargeInput input);
        void Delete(string id );

        UsersCharge GetModel(string Id);
        
        PagedData<UsersCharge> GetPageData(Pagination page, int ChargeSort = -2, string keyword = "");

        PagedData<UsersChargeInfo> GetPageList(Pagination page, int ChargeSort = -2, string keyword = "",string UserID="",string Year="",string Month="");
    }

    public class UsersChargeService : AppServiceBase<UsersCharge>, IUsersChargeService
    {
        public UsersChargeService(IDbContext dbContext, IServiceProvider services) : base(dbContext, services)
        {
        }


        public decimal GetLeft(string UserID)
        {
            string sql = "select f_users_charge_left('"+ UserID + "') as a";

            decimal left = this.DbContext.SqlQuery<decimal>(sql).FirstOrDefault();
            return left;
        }
         
        public UsersCharge Add(AddUsersChargeInput input)
        {
            UsersCharge NewModle= this.InsertFromDto(input);
            decimal left = GetLeft(input.UserID);
            this.DbContext.Update<UsersCharge>(a => a.Id == NewModle.Id, a => new UsersCharge()
            {
                Balance = left
            });

            return NewModle;
        }
        public void Update(UpdateUsersChargeInput input)
        {
            this.UpdateFromDto(input);


            decimal left = GetLeft(input.UserID);
            this.DbContext.Update<UsersCharge>(a => a.Id == input.Id, a => new UsersCharge()
            {
                Balance = left
            });

        }

        public UsersCharge GetModel(string Id)
        {
            return  this.Query.Where(a => a.Id == Id).FirstOrDefault();
        }

        public void Delete(string id)
        {
            //this.DbContext.Delete<UsersCharge>(a => a.Id == id);
            this.DbContext.Update<UsersCharge>(a => a.Id==id, a => new UsersCharge()
            {
                ChargeSort = 2                 
            });
        }


        public PagedData<UsersCharge> GetPageData(Pagination page,int ChargeSort = -2, string keyword="")
        {
            var q = this.DbContext.Query<UsersCharge>();
            q = q.WhereIfNotNullOrEmpty(keyword, a => a.ChargeCode.Contains(keyword) );
            if(ChargeSort > -2)
            {
                q = q.Where(a => a.ChargeSort == ChargeSort);
            }
            
            PagedData<UsersCharge> pagedData = q.TakePageData(page);
            return pagedData;
        }

        public PagedData<UsersChargeInfo> GetPageList(Pagination page, int ChargeSort = -2, string keyword="", string UserID = "", string Year = "", string Month = "")
        {
            string strFileds = " a.*,b.TrueName,b.Mobile  ";
            string strWhere = "1=1 ";
            if (ChargeSort > -2)
            {
                strWhere += " and a.ChargeSort=" + ChargeSort;
            }
             
            if (!string.IsNullOrEmpty(keyword))
            {
                strWhere += " and ( b.Mobile like '%" + keyword + "%' or b.TrueName like '%" + keyword + "%' or a.ChargeCode like '%" + keyword + "%')    ";
            }
            if (!string.IsNullOrEmpty(UserID))
            {
                strWhere += " and   a.UserID ='" + UserID + "'     ";
            }

            if(!string.IsNullOrEmpty(Year)&&!string.IsNullOrEmpty(Month))
            {
                string time1 = Year + "-" + Month + "-01 00:00:01";

                DateTime d1 = new DateTime(int.Parse(Year),int.Parse(Month),1);
                DateTime d2 = d1.AddMonths(1).AddDays(-1);

                string time2 = d2.ToString("yyyy-MM-dd")+" 23:59:59";
                strWhere += " and a.CreateDate between '"+ time1 + "' and '"+time2+"'";
            }


            DbParam _totalcount = new DbParam("?_totalcount", null, typeof(int)) { Direction = ParamDirection.Output };
            DbParam _pagecount = new DbParam("?_pagecount", null, typeof(int)) { Direction = ParamDirection.Output };

            DbParam[] dbs = new DbParam[] {
                new DbParam("?_fields", strFileds),
                new DbParam("?_tables", " users_charge a LEFT JOIN users b ON a.UserID=b.Id "),
                new DbParam("?_where",strWhere),
                new DbParam("?_orderby", "a.CreateDate desc"),
                new DbParam("?_pageindex", page.Page),
                new DbParam("?_pageSize", page.PageSize),
                _totalcount,
                _pagecount
            };

            List<UsersChargeInfo> list = this.DbContext.SqlQuery<UsersChargeInfo>("sp_viewPage", System.Data.CommandType.StoredProcedure, dbs).ToList();

            PagedData<UsersChargeInfo> pagedData = new PagedData<UsersChargeInfo>();
            pagedData.CurrentPage = page.Page;
            pagedData.Models = list;
            pagedData.PageSize = page.PageSize;
            pagedData.TotalCount = Convert.ToInt32(_totalcount.Value);
            pagedData.TotalPage = Convert.ToInt32(_pagecount.Value);




            return pagedData;
        }



    }

}
